package com.dh.project.utils;

import com.dh.project.model.push.PushAlias;
import com.dh.project.model.push.PushAll;

import java.io.IOException;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Mc on 2016/10/13.
 */
public class PushUtil {

    private final static String APP_KEY = "c9189bf6313ef71203ea75fc"; //极光key
    private final static String SMART_SECRET = "3901c92a3e87f974bb14eabc"; //极光秘钥
    private final static String PUSH_URL = "https://api.jpush.cn/v3/push"; //极光REST API地址

    private final static MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");


    /**
     * 单推
     *
     * @param alias  推送标识
     * @param msg    状态栏展示消息
     * @param extras 隐藏对象
     * @param apn    是否生产环境  false开发 true生产
     */
    public static void pushOne(List<String> alias, String msg, Object extras, boolean apn) {
        PushAlias pushAlias1 = new PushAlias(alias, msg, extras, 1);//android
        PushAlias pushAlias2 = new PushAlias(alias, msg, extras, 2);//ios
        pushAlias2.getOptions().setApns_production(apn);
        push(JsonUtil.toJson(pushAlias1));
        push(JsonUtil.toJson(pushAlias2));
    }

    /**
     * 全推
     *
     * @param msg    状态栏展示消息
     * @param extras 隐藏对象
     * @param apn    是否生产环境  false开发 true生产
     */
    public static void pushAll(String msg, Object extras, boolean apn) {
        PushAll all1 = new PushAll(msg, extras, 1);
        PushAll all2 = new PushAll(msg, extras, 2);
        all2.getOptions().setApns_production(apn);
        push(JsonUtil.toJson(all1));
        push(JsonUtil.toJson(all2));

    }

    private static void push(String msg) {

        Request request = new Request.Builder()
                .url(PUSH_URL)
                .post(RequestBody.create(MEDIA_TYPE, msg))
                .header("Authorization", "Basic " + StringUtil.getBase64(APP_KEY + ":" + SMART_SECRET))
                .build();

        LogUtil.i("请求头: " + request.headers().toString());
        LogUtil.i("请求体: " + msg);
        OkHttpClient okHttpClient = new OkHttpClient();
        try {
            Response res = okHttpClient.newCall(request).execute();
            LogUtil.i("返回体: " + res.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
